<template>
  <div class="page-container pet-page">
    <div class="notification-container"></div>
    <div v-if="!pet">
      <pet-adopt-panel @pet-adopted="handlePetAdopted" />
    </div>

    <div v-else class="pet-details">
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="pet-card card">
            <div class="pet-avatar">
              <div v-if="getPetIcon(pet.species)" class="pet-emoji">{{ getPetIcon(pet.species) }}</div>
            </div>
            <h2 class="text-center mt-4">{{ pet.name }}</h2>
            <div class="pet-level text-center mb-1">等级 Lv.{{ level }}</div>
            <div class="pet-species text-center mb-2">{{ getPetSpeciesLabel(pet.species) }}</div>
            <div class="pet-introduction text-center mb-4" v-if="pet.introduction">
              <div class="introduction-text">{{ pet.introduction }}</div>
            </div>
            <div class="pet-stats mt-4">
              <el-progress 
                :percentage="expPercent" 
                :format="() => `${exp}/${nextLevelExp} (${expPercent}%)`"
                :stroke-width="16"
                style="margin-bottom: 24px;"
              />
              <div class="stat-item mt-4">
                <span class="label">饥饿值</span>
                <el-progress 
                  :percentage="pet.hunger"
                  :status="getStatusType(pet.hunger)"
                  :stroke-width="16"
                  style="width: 70%; margin-left: 16px;"
                >
                  <template #default="{ percentage }">
                    {{ percentage }}%
                  </template>
                </el-progress>
              </div>
              <div class="stat-item mt-4">
                <span class="label">心情</span>
                <el-progress 
                  :percentage="pet.happiness"
                  :status="getStatusType(pet.happiness)"
                  :stroke-width="16"
                  style="width: 70%; margin-left: 16px;"
                >
                  <template #default="{ percentage }">
                    {{ percentage }}%
                  </template>
                </el-progress>
              </div>
              <div class="stat-item mt-4">
                <span class="label">体力</span>
                <el-progress 
                  :percentage="pet.energy"
                  :status="getStatusType(pet.energy)"
                  :stroke-width="16"
                  style="width: 70%; margin-left: 16px;"
                >
                  <template #default="{ percentage }">
                    {{ percentage }}%
                  </template>
                </el-progress>
              </div>
            </div>
          </div>
        </el-col>

        <el-col :span="16">
          <div class="actions-card card">
            <h3>互动</h3>
            <div class="actions-grid">
              <el-button 
                v-for="action in actions" 
                :key="action.type"
                :type="action.type"
                :icon="action.icon"
                :disabled="isActionDisabled(action)"
                :loading="loading && action.label === '训练'"
                @click="handleAction(action)"
              >
                {{ action.label }}
              </el-button>
            </div>
            <el-divider />
            <el-button type="danger" plain class="abandon-btn" @click="showAbandonConfirm = true">弃养宠物</el-button>
            <el-dialog v-model="showAbandonConfirm" title="确认弃养" width="340px" :close-on-click-modal="false">
              <div>确定要弃养当前宠物吗？此操作不可恢复。</div>
              <template #footer>
                <el-button @click="showAbandonConfirm = false">取消</el-button>
                <el-button type="danger" @click="abandonPet" :loading="abandonLoading">确认弃养</el-button>
              </template>
            </el-dialog>
          </div>

          <div class="status-card card mt-4">
            <h3>状态日志</h3>
            <el-timeline v-if="statusLogs.length">
              <el-timeline-item
                v-for="log in statusLogs"
                :key="log.id"
                :timestamp="log.time"
                :type="log.type"
              >
                {{ log.content }}
              </el-timeline-item>
            </el-timeline>
            <el-empty v-else description="暂无状态记录" />
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { usePetStore } from '../stores/pet'
import { ElMessage } from 'element-plus'
import { calculateExperienceForLevel } from '../utils/helpers'
import { useRouter } from 'vue-router'
import PetAdoptPanel from './PetAdoptPanel.vue'

export default {
  name: 'PetView',
  components: {
    PetAdoptPanel
  },
  setup() {
    const petStore = usePetStore()
    const formRef = ref()
    const loading = ref(false)
    const selectedPet = ref(null)
    const router = useRouter()

    const petCandidates = ref([])
    const statusLogs = computed(() => petStore.statusLogs)  // 使用 store 中的状态日志

    // 处理宠物领养成功事件
    const handlePetAdopted = async () => {
      try {
        await petStore.fetchPet()
      } catch (error) {
        console.error('Failed to fetch pet after adoption:', error)
      }
    }

    const form = ref({
      name: '',
      introduction: ''
    })

    const pet = computed(() => petStore.pet)
    const exp = computed(() => pet.value?.experience ?? 0)
    const level = computed(() => pet.value?.level ?? 1)
    const nextLevelExp = computed(() => calculateExperienceForLevel(level.value))
    const expPercent = computed(() => Math.floor((exp.value / nextLevelExp.value) * 100))

    const rules = {
      name: [
        { required: true, message: '请输入宠物名称', trigger: 'blur' },
        { min: 2, message: '名称至少2个字符', trigger: 'blur' }
      ],
      introduction: [
        { max: 100, message: '介绍不能超过100个字符', trigger: 'blur' }
      ]
    }

    const showMessage = (message, type = 'success') => {
      // 获取所有现有的消息
      const messages = document.querySelectorAll('.el-message');
      // 关闭所有现有的消息
      messages.forEach(msg => {
        msg.close && msg.close();
      });
      
      // 显示新消息
      ElMessage({
        message,
        type,
        duration: 2000
      });
    };

    // 处理喂食动作
    const handleFeeding = async () => {
      try {
        await petStore.feedPet();
        // 添加到状态日志
        petStore.addStatusLog({
          id: Date.now(),
          content: '给宠物喂食了',
          type: 'success',
          time: new Date().toLocaleTimeString()
        });
      } catch (error) {
        console.error('Feed pet error:', error);
      }
    };

    // 处理训练动作
    const handleTraining = async () => {
      try {
        loading.value = true;
        await petStore.trainPet();
        // 立即更新宠物状态
        await petStore.fetchPet();
      } catch (error) {
        console.error('Train pet error:', error);
      } finally {
        loading.value = false;
      }
    };

    // 处理互动按钮点击
    const handleAction = async (action) => {
      if (action.label === '喂食') {
        await handleFeeding()
      } else if (action.label === '训练') {
        await handleTraining()
      }
    }

    // 判断动作是否禁用
    const isActionDisabled = (action) => {
      if (action.label === '喂食') {
        return pet.value?.hunger >= 100
      } else if (action.label === '训练') {
        return pet.value?.energy < 10 || pet.value?.hunger < 5
      }
      return false
    }

    onMounted(async () => {
      try {
        loading.value = true
        await petStore.fetchPet()
        petCandidates.value = await petStore.fetchPetCandidates()
        if (pet.value) {
          petStore.startAutoUpdate()  // 启动自动更新
        }
      } catch (error) {
        console.error('Failed to fetch pet candidates:', error)
      } finally {
        loading.value = false
      }
    })

    // 组件卸载时停止自动更新
    onUnmounted(() => {
      petStore.stopAutoUpdate()
    })

    const actions = [
      { type: 'primary', label: '喂食', icon: 'Food' },
      { type: 'success', label: '训练', icon: 'Star' }
    ]

    const showAbandonConfirm = ref(false)
    const abandonLoading = ref(false)

    const abandonPet = async () => {
      if (!pet.value) return
      abandonLoading.value = true
      try {
        await petStore.abandonPet(pet.value.id)
        showAbandonConfirm.value = false
        router.push('/')
      } catch (e) {
        // 错误消息已经在 store 中处理
      } finally {
        abandonLoading.value = false
      }
    }

    const getPetIcon = (species) => {
      const icons = {
        cat: '🐱',
        dog: '🐶',
        rabbit: '🐰',
        hamster: '🐹',
        parrot: '🦜'
      }
      return icons[species] || ''
    }

    const getPetSpeciesLabel = (species) => {
      const labels = {
        cat: '猫咪',
        dog: '狗狗',
        rabbit: '兔子',
        hamster: '仓鼠',
        parrot: '鹦鹉'
      }
      return labels[species] || species
    }

    // 状态条颜色映射
    const getStatusType = (value) => {
      if (value >= 70) return 'success'
      if (value >= 40) return 'warning'
      return 'exception'
    }

    // 新增 selectPet 方法
    const selectPet = (pet) => {
      selectedPet.value = selectedPet.value?.id === pet.id ? null : pet
    }

    return {
      pet,
      exp,
      level,
      nextLevelExp,
      expPercent,
      form,
      rules,
      loading,
      formRef,
      handlePetAdopted,
      petCandidates,
      selectedPet,
      selectPet,
      handleAction,
      isActionDisabled,
      actions,
      statusLogs,
      showAbandonConfirm,
      abandonLoading,
      abandonPet,
      getPetIcon,
      getPetSpeciesLabel,
      getStatusType
    }
  }
}
</script>

<style scoped>
.pet-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  transition: all 0.3s ease;
  border: 2px solid transparent;
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.stat-item {
  display: flex;
  align-items: center;
}

.stat-item .label {
  width: 60px;
  margin-right: 10px;
}

.actions-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
  margin-top: 20px;
}

.status-card {
  height: 400px;
  overflow-y: auto;
}

.pet-emoji {
  display: inline;
  background: none;
  border: none;
  width: auto;
  height: auto;
  min-width: 0;
  min-height: 0;
  box-shadow: none;
  padding: 0;
  margin: 0;
  font-size: 64px;
}

.abandon-btn {
  margin-top: 20px;
  width: 100%;
}

.pet-introduction {
  padding: 10px 15px;
  background-color: rgba(64, 158, 255, 0.05);
  border-radius: 8px;
}

.introduction-text {
  color: #606266;
  font-size: 14px;
  line-height: 1.6;
  text-align: left;
}

.notification-container {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 9999;
  pointer-events: none;
  width: 200px;
}

.custom-notification {
  background: rgba(103, 194, 58, 0.9);
  color: white;
  padding: 10px 15px;
  border-radius: 4px;
  text-align: center;
  animation: fadeInOut 2s ease-in-out;
  margin-bottom: 10px;
  backdrop-filter: blur(5px);
}

@keyframes fadeInOut {
  0% {
    opacity: 0;
    transform: translateY(20px);
  }
  20% {
    opacity: 1;
    transform: translateY(0);
  }
  80% {
    opacity: 1;
    transform: translateY(0);
  }
  100% {
    opacity: 0;
    transform: translateY(-20px);
  }
}

.custom-notification-success {
  background: rgba(103, 194, 58, 0.9);
}

.custom-notification-warning {
  background: rgba(230, 162, 60, 0.9);
}

.custom-notification-error {
  background: rgba(245, 108, 108, 0.9);
}

/* 限制 ElMessage 的显示范围 */
:deep(.el-message) {
  top: 20px !important;
  max-height: calc(100vh - 200px);
  overflow: hidden;
}

/* 当有多个消息时，限制显示数量 */
:deep(.el-message + .el-message) {
  display: none;
}
</style>
